<template>
  <div>
    <div class="am-u-sm-12 am-u-md-12 am-u-lg-12">
      <div class="widget am-cf">
        <div class="widget-head am-cf">
          <div class="widget-title  am-cf">新增班级申请</div>
        </div>
        <div class="widget-body  am-fr">

          <div class="am-u-sm-12 am-form ">

            <div class="am-u-sm-12 am-u-md-12 am-u-lg-3">
              <div class="am-form-group">
                <select2
                  v-model="query.areaTeamId"
                  :options="areaTeams"
                >
                  <option
                    value=""
                    disabled
                  >区域</option>
                </select2>
              </div>
            </div>
            <el-select
              size="small"
              class="am-u-sm-12 am-u-md-12 am-u-lg-3 am-form-group"
              :disabled="busTeams.length === 0"
              v-model="query.busTeamId"
              placeholder="请选择业务组"
            >
              <el-option
                v-for="item in busTeams"
                :key="item.busTeamId"
                :label="item.name"
                :value="item.busTeamId"
              >
              </el-option>
            </el-select>
            <el-select
              :disabled="periodIds.length === 0"
              size="small"
              class="am-u-sm-12 am-u-md-12 am-u-lg-3 am-form-group"
              v-model="query.periodId"
              placeholder="请选择期数"
            >
              <el-option
                v-for="item in periodIds"
                :key="item.periodId"
                :label="item.periodName"
                :value="item.periodId"
              >
              </el-option>
            </el-select>
            <el-select
              size="small"
              class="am-u-sm-12 am-u-md-12 am-u-lg-3 am-form-group"
              v-model="query.auditStatus"
              placeholder="选择审核状态"
            >
              <el-option
                label="未审核"
                value="0"
              >
              </el-option>
              <el-option
                label="审核通过"
                value="1"
              >
              </el-option>
              <el-option
                label="审核不通过"
                value="2"
              >
              </el-option>
            </el-select>
            <div class="am-u-sm-12 am-u-md-12 am-u-lg-3">
              <div class="am-form-group">
                <el-date-picker
                  v-model="startTime"
                  type="daterange"
                  placeholder="申请日期"
                >
                </el-date-picker>
              </div>
            </div>

            <div class="am-u-sm-12 am-u-md-12 am-u-lg-3 am-u-end">
              <div class="am-form-group">
                <button
                  type="button"
                  class="am-btn am-btn-default am-btn-success"
                  @click="search"
                ><span class="am-icon-search"></span>&nbsp;查询
                </button>

                <button
                  type="button"
                  class="am-btn am-btn-default am-btn-success"
                  @click="exportFile"
                >导出
                </button>

                <button
                  type="button"
                  class="am-btn am-btn-default am-btn-success"
                  @click="addNewApply"
                >新建申请
                </button>
              </div>
            </div>
          </div>

          <div class="am-u-sm-12">
            <el-table
              :data="tableData"
              border
              stripe
              style="min-width: 100%"
            >
              <el-table-column
                prop="areaTeamName"
                label="区域"
                min-width="120"
              >
              </el-table-column>
              <el-table-column
                prop="periodName"
                label="期数"
                min-width="120"
              >
              </el-table-column>
              <el-table-column
                prop="busTeamName"
                label="业务组"
                min-width="200"
              >
              </el-table-column>
              <el-table-column
                prop="gradeName"
                label="年级"
                min-width="100"
              >
              </el-table-column>
              <el-table-column
                prop="subjectName"
                label="科目"
                min-width="100"
              >
              </el-table-column>
              <el-table-column
                prop="level"
                label="层级"
                min-width="180"
              >
                <template scope="scope">
                  {{scope.row.level | getRegLevelVal }}
                </template>

              </el-table-column>
              <el-table-column
                prop="className"
                label="班级名称"
                min-width="100"
              >
              </el-table-column>
              <el-table-column
                prop="startCourseTime"
                label="开课日期"
                min-width="180"
              >
                <template scope="scope">
                  {{scope.row.startCourseTime | formatDate }}
                </template>
              </el-table-column>
              <el-table-column
                prop="studyingTime"
                label="开课时间"
                min-width="180"
              >
              </el-table-column>
              <el-table-column
                prop="teacherName"
                label="主讲老师"
                min-width="100"
              >
              </el-table-column>
              <el-table-column
                prop="applyReason"
                label="增开原因"
                min-width="300"
              >
              </el-table-column>
              <el-table-column
                prop="proposerName"
                label="申请人"
                min-width="100"
              >
              </el-table-column>
              <el-table-column
                prop="createTime"
                label="申请时间"
                min-width="200"
              >
                <template scope="scope">
                  {{scope.row.createTime | formatTime }}
                </template>
              </el-table-column>
              <el-table-column
                prop="auditStatus"
                label="审核状态"
                min-width="110"
              >
                <template scope="scope">
                  {{scope.row.auditStatus == 0 ? '未审核': (scope.row.auditStatus == 1 ? '审核通过' : '审核不通过')}}
                </template>
              </el-table-column>
              <el-table-column
                prop="auditReason"
                label="审核理由"
                min-width="300"
              >
              </el-table-column>
              <el-table-column
                prop="busTeamName"
                label="操作"
                min-width="220"
                fixed="right"
              >
                <template scope="scope">
                  <el-button
                    size="small"
                    @click="checking(scope.row)"
                    v-if="scope.row.auditStatus == 0 && hasPermission('audit')"
                  >审核</el-button>
                  <el-button
                    size="small"
                    @click="looking(scope.row)"
                  >查看</el-button>
                  <el-button
                    size="small"
                    @click="inProve(scope.row)"
                    v-if="scope.row.auditStatus == 1 && scope.row.generateClassStatus == 0 && hasPermission('createClass')"
                  >完善信息</el-button>
                  <el-button
                    size="small"
                    @click="editData(scope.row)"
                    v-if="scope.row.auditStatus == 0"
                  >修改</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="am-u-lg-12 am-cf">

            <div class="am-fr">
              <pagination
                @pageSizeChange="pageSize = arguments[0]"
                isShowPageSize
                v-bind:total="total"
                v-bind:pageNo="pageNo"
                v-bind:pageSize="pageSize"
                @paging="loadTableData"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      :title="addNewApplyMode === 'new' ?'新建申请' : '修改'"
      :visible="addNewApplyShow"
      :key="addNewApplyShow"
      size="small"
      :before-close="addNewApplyClose"
      class="elDlog"
    >
      <el-form
        ref="applyClassForm"
        :model="applyClassForm"
        label-width="80px"
        :rules="applyClassRules"
        v-loading="applyLoading"
      >
        <el-form-item
          label="区域"
          prop="areaTeamId"
        >
          <el-select v-model="applyClassForm.areaTeamId">
            <el-option
              v-for="item in areaTeams"
              :key="item.value"
              :value="item.value"
              :label="item.text"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="期数"
          prop="periodId"
        >
          <el-select v-model="applyClassForm.periodId">
            <el-option
              v-for="item in applyClassFormPeriodIds"
              :key="item.periodId"
              :label="item.periodName"
              :value="item.periodId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="业务组"
          prop="busTeamId"
        >
          <el-select v-model="applyClassForm.busTeamId">
            <el-option
              v-for="item in applyClassBusTeams"
              :key="item.busTeamId"
              :label="item.name"
              :value="item.busTeamId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="年级"
          prop="gradeId"
        >
          <el-select v-model="applyClassForm.gradeId">
            <el-option
              v-for="item in grades"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="科目"
          prop="subjectId"
        >
          <el-select v-model="applyClassForm.subjectId">
            <el-option
              v-for="item in subjects"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="层级"
          prop="level"
        >
          <el-select v-model="applyClassForm.level">
            <el-option
              v-for="item in regLevels"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <div style="display:inline-block;margin-left:30px;color:blue">
            <el-button
              @click="lookBase"
              :disabled="!(applyClassForm.level && applyClassForm.periodId  && applyClassForm.busTeamId && applyClassForm.gradeId && applyClassForm.subjectId )"
            >查看基础指标</el-button>
          </div>
        </el-form-item>
        <el-form-item
          label="班级名称"
          prop="className"
        >
          <el-input
            v-model="applyClassForm.className"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="首讲日期"
          prop="startCourseTime"
        >
          <el-date-picker
            size="small"
            v-model="applyClassForm.startCourseTime"
            type="date"
            :editable="false"
            placeholder="选择日期范围"
          ></el-date-picker>
        </el-form-item>
        <el-form-item
          label="首讲时间"
          prop="studyingTime"
        >
          <div class="am-u-sm-4 input-field">
            <time-picker
              v-model="applyClassForm.studyingTime"
              class="aTimePicker"
            ></time-picker>
          </div>

          <!-- <el-time-picker
            v-model="applyClassForm.studyingTime"
            is-range
            :editable="true"
            format='HH:mm'
            value-format="HH:mm"
            placeholder="选择时间"
          ></el-time-picker>
          <div>格式：24小时制</div> -->
        </el-form-item>
        <el-form-item label="任课老师">
          <div style="width: 300px;display:inline-block">
            <el-input
              v-model="applyClassForm.teacherName"
              disabled
            ></el-input>
          </div>
          <div style="display:inline-block; margin-left:30px">
            <el-button
              @click="showTeacher"
              :disabled="!(applyClassForm.areaTeamId && applyClassForm.gradeId)"
            >请选择</el-button>
          </div>
        </el-form-item>
        <el-form-item
          label="增开原因"
          prop="applyReason"
        >
          <el-input
            v-model="applyClassForm.applyReason"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="large"
            @click="onApplyClassSubmit"
          >提交</el-button>

        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      title="选择老师"
      :visible="isModalAlert"
      :key="isModalAlert"
      size="large"
      :before-close="hideModalAlert"
    >
      <selectTeacher
        :query="applyClassForm"
        @selectConfirm="selectConfirmTeacher"
      ></selectTeacher>
    </el-dialog>
    <checkApplyClass
      :data="checkItemData"
      :isShow="checkModal"
      :mode="checkModalType"
      :base="checkModalBaseData"
      @checkModalClose="checkClose"
      @selectTeacher="showTeacher"
      :key="checkModal"
    ></checkApplyClass>
    <el-dialog
      title="基础指标"
      :visible="baseShow"
      :key="baseShow"
      size="small"
      :before-close="hidebaseShow"
      class="elDlog"
    >
      <div>同类别班级数量：{{checkModalBaseData.classNum}}</div>
      <div>同类别班级报读人数之和：{{checkModalBaseData.regNum}}</div>
      <div>同类别班级平均满班率：{{`${Number(checkModalBaseData.classNum) ? (checkModalBaseData.regNum/(checkModalBaseData.classNum *28)*100).toFixed(2) : 0}%`}}</div>
    </el-dialog>
    <checkForm
      :data="checkItemData"
      @selectTeacher="showTeacher"
      :key="checkItemData.applyClassId"
      @finishUpdated="loadTableData"
      :inProveModal="inProveModal"
      @inProveClose="closeInprove"
    >
    </checkForm>
  </div>
</template>

<script>
import io from '../../lib/io'
import { regLevels } from '../../lib/global/index.js'
import moment from 'moment'
import Pagination from '../base/Pagination'
import selectTeacher from '../base/selectTeacher'
import checkApplyClass from './applyClass/checkApplyClass'
import checkForm from './applyClass/checkForm'

export default {
  data() {
    return {
      applyLoading: false,
      isModalAlert: false,
      regLevels,
      addNewApplyMode: 'new',
      addNewApplyShow: false,
      applyClassFormPeriodIds: [],
      applyClassForm: {
        areaTeamId: '',
        periodId: '',
        busTeamId: '',
        gradeId: '',
        level: '',
        subjectId: '',
        startCourseTime: '',
        studyingTime: '',
        teacherId: '',
        teacherName: '',
        applyReason: '',
        applyClassId: ''
      },
      tableData: [],
      total: 0,
      pageSize: 10,
      pageNo: 1,
      startTime: [],
      query: {
        areaTeamId:
          (window.config.areaTeams[0] &&
            window.config.areaTeams[0].areaTeamId) ||
          '',
        busTeamId: '',
        periodId: '',
        startDate: '',
        endDate: '',
        auditStatus: ''
      },
      year: moment().format('YYYY'),
      periodIds: [],
      applyClassRules: {
        areaTeamId: [
          { required: true, message: '请选择地区', trigger: 'change' }
        ],
        periodId: [
          { required: true, message: '请选择期数', trigger: 'change' }
        ],
        busTeamId: [
          {
            required: true,
            message: '请选择业务组',
            trigger: 'change'
          }
        ],
        level: [
          {
            required: true,
            message: '请选择层级',
            trigger: 'change'
          }
        ],
        gradeId: [
          {
            required: true,
            message: '请选择年级',
            trigger: 'change'
          }
        ],
        className: [{ required: true, message: '请填写班级', trigger: 'blur' }],
        subjectId: [
          { required: true, message: '请选择科目', trigger: 'change' }
        ],
        startCourseTime: [
          {
            required: true,
            type: 'date',
            message: '请选择首讲日期',
            trigger: 'blur'
          }
        ],
        studyingTime: [
          {
            required: true,
            // type: 'array',
            message: '请选择首讲时间',
            trigger: 'blur'
          }
        ],
        applyReason: [
          { required: true, message: '请填写增开原因', trigger: 'blur' }
        ]
      },
      checkItemData: {},
      checkModal: false,
      checkModalType: '',
      checkModalBaseData: {},
      selectTeacherType: '',
      baseShow: false,
      inProveModal: false
    }
  },
  components: {
    Pagination,
    selectTeacher,
    checkApplyClass,
    checkForm
  },
  mounted() {
    $(window).smoothScroll()
  },
  created() {
    this.loadTableData(this.pageNo)
    this.loadPeriodByYear()
  },
  watch: {
    'applyClassForm.areaTeamId': function(val, oldVal) {
      if (!this.addNewApplyShow) {
        return
      }
      if (oldVal) {
        this.applyClassForm.periodId = ''
      }
      this.loadAddClassPerioId()
    },
    'query.areaTeamId': function(val, oldVal) {
      this.query.periodId = ''
      this.loadPeriodByYear()
    }
  },
  computed: {
    areaTeams: function() {
      var options = (this.$root.config.areaTeams || []).map(function(item) {
        return { value: item.areaTeamId, text: item.name }
      })
      return options
    },
    busTeams: function() {
      return this.query.areaTeamId
        ? this.$root.config.groupBusTeams[this.query.areaTeamId] || []
        : []
    },
    applyClassBusTeams: function() {
      return this.applyClassForm.areaTeamId
        ? this.$root.config.groupBusTeams[this.applyClassForm.areaTeamId] || []
        : []
    },
    grades() {
      return this.$root.config.grades.map(function(item) {
        return { value: item.gradeId, label: item.gradeName }
      })
    },
    subjects() {
      return this.$root.config.subjects.map(function(item) {
        return { value: item.subjectId, label: item.subjectName }
      })
    }
  },
  methods: {
    inProve(itemData) {
      this.checkItemData = itemData
      this.inProveModal = true
    },
    closeInprove() {
      this.inProveModal = false
    },
    lookBase() {
      this.baseShow = true
      let findQuery = {
        periodId: this.applyClassForm.periodId,
        busTeamId: this.applyClassForm.busTeamId,
        gradeId: this.applyClassForm.gradeId,
        subjectId: this.applyClassForm.subjectId,
        level: this.applyClassForm.level
      }
      this.getBase(findQuery)
    },
    hidebaseShow() {
      this.baseShow = false
    },
    getBase(query) {
      io.post(io.findRegNumClassNum, query, ret => {
        if (ret.success) {
          this.checkModalBaseData = ret.data
        } else {
          this.$alert(ret.desc)
        }
      })
    },
    checking(itemData) {
      this.showCheckModal('check', itemData)
    },
    looking(itemData) {
      this.showCheckModal('look', itemData)
    },
    checkClose() {
      this.checkModal = false
      this.search()
    },
    showCheckModal(type, itemData) {
      this.checkItemData = itemData
      this.checkModal = true
      this.checkModalType = type
      let findQuery = {
        periodId: itemData.periodId,
        busTeamId: itemData.busTeamId,
        gradeId: itemData.gradeId,
        subjectId: itemData.subjectId,
        level: itemData.level
      }
      this.getBase(findQuery)
    },
    onApplyClassSubmit() {
      this.$refs.applyClassForm.validate(valid => {

        if (this.applyClassForm.studyingTime) {

          let startTime = new Date(
            `2019-6-6 ${this.applyClassForm.studyingTime.split('-')[0]}`
          )
          let endTime = new Date(
            `2019-6-6 ${this.applyClassForm.studyingTime.split('-')[1]}`
          )
          if (startTime.getTime() > endTime.getTime()) {
            alert('开始时间不能大于结束时间')
            return
          }
        }
        if (valid) {
          let formData = {
            ...this.applyClassForm
          }
          formData.startCourseTime = moment(formData.startCourseTime).format(
            'YYYY-MM-DD'
          )

          this.applyLoading = true
          io.post(
            io.saveApplyClass,
            formData,
            ret => {
              this.applyLoading = false
              if (ret.success) {
                this.addNewApplyClose()
                this.$alert('添加成功')
                this.loadTableData()
              } else {
                alert(ret.desc)
              }
            },
            () => {
              this.applyLoading = false
            }
          )
        }
      })
    },
    selectConfirmTeacher(item) {
      if (this.selectTeacherType === 'checkModal') {
        this.$emit('checkModalSuccess', item)
      } else {
        this.applyClassForm.teacherId = item.teacherId
        this.applyClassForm.teacherName = item.teacherName
      }
      this.hideModalAlert()
    },
    showTeacher(type) {
      if (type) {
        this.selectTeacherType = type
      }
      this.isModalAlert = true
    },
    hideModalAlert() {
      this.isModalAlert = false
    },
    addNewApplyClose() {
      this.addNewApplyShow = false
      this.resetApplyForm()
    },
    resetApplyForm() {
      this.applyClassForm = {
        areaTeamId: '',
        periodId: '',
        busTeamId: '',
        gradeId: '',
        level: '',
        subjectId: '',
        startCourseTime: '',
        studyingTime: '',
        teacherId: '',
        teacherName: '',
        applyReason: '',
        applyClassId: ''
      }
    },
    editData(row) {
      this.applyClassForm = {
        ...row
      }
      this.applyClassForm.startCourseTime = new Date(Number(row.startCourseTime))
      this.addNewApplyMode = 'edit'
      this.addNewApplyShow = true
    },
    addNewApply() {
      this.addNewApplyMode = 'new'
      this.resetApplyForm()
      this.addNewApplyShow = true
    },
    exportFile() {
      var _this = this
      _this.pageNo = this.pageNo || 1
      let data = Object.assign({}, this.query, {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        busTeamId: this.query.busTeamId,
        periodId: this.query.periodId,
        startDate:
          this.query.time && this.query.time[0]
            ? moment(this.query.time[0]).format('YYYY-MM-DD')
            : '',
        endDate:
          this.query.time && this.query.time[0]
            ? moment(this.query.time[1]).format('YYYY-MM-DD')
            : ''
      })
      io.downloadFile(io.exportApplyClassDetailList, data, function(ret) {
        if (!ret.success) {
          _this.$alert(ret.desc)
        }
      })
    },
    loadPeriod(areaTeamId) {
      return new Promise((resolve, reject) => {
        io.post(
          io.apiAdminPeriodListForAreaTeam,
          {
            areaTeamId: areaTeamId
          },
          ret => {
            if (ret.success) {
              if (ret.data.length === 0) {
                this.$alert('当前没有设置期数')
              }
              resolve(ret.data)
            } else {
              this.$alert(ret.desc)
            }
          }
        )
      })
    },
    loadAddClassPerioId() {
      this.loadPeriod(this.applyClassForm.areaTeamId).then(data => {
        this.applyClassFormPeriodIds = data
      })
    },
    loadPeriodByYear() {
      this.loadPeriod(this.query.areaTeamId).then(data => {
        this.periodIds = data
      })
    },
    search: function() {
      this.loadTableData(1)
    },
    loadTableData: function(pageNo) {
      var _this = this
      _this.pageNo = pageNo || _this.pageNo || 1
      let data = Object.assign({}, this.query, {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        busTeamId: this.query.busTeamId,
        periodId: this.query.periodId,
        startDate:
          this.startTime && this.startTime[0]
            ? moment(this.startTime[0]).format('YYYY-MM-DD')
            : '',
        endDate:
          this.startTime && this.startTime[0]
            ? moment(this.startTime[1]).format('YYYY-MM-DD')
            : ''
      })
      io.post(io.findApplyClassDetailPage, data, function(ret) {
        if (ret.success) {
          _this.total = ret.data.total
          _this.tableData = ret.data.list
        } else {
          _this.$alert(ret.desc)
        }
      })
    }
  }
}
</script>
<style lang="less">
.am-form input[type='text'][readonly] {
  cursor: text;
  background-color: transparent;
}
.add-check {
  .el-date-editor.el-input {
    width: 60%;
  }
  .el-checkbox {
    margin-left: 10px;
    color: red;
  }
}
.aTimePicker {
  .am-margin-top-xs {
    text-align: center;
  }
}
// .elDlog{
//   z-index: 1203!important;
// }
// .v-modal{
//   z-index: 1201!important;
// }
</style>
<style lang="less" scoped>
</style>

